<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Gallery extends Admin_Controller{

    function __construct(){
        parent::__construct();
        $this->load->model(array('Mgallery','Mcataloguemedia'));
    }

    public function index(){
        $this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery'),base_url().'admincp/gallery');
        if($this->input->is_ajax_request()){
            $output = $this->Mgallery->listGallery();
            $this->output->set_output(json_encode($output));
        }else{
            $data['template']="gallery/view";
            $data['title_page']='<i class="icon20 i-image-5"></i> '.trans('title_gallery');
            $this->load->view("admincp/template",$data);
        }
    }

    public function add(){
        $this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery'),base_url().'admincp/gallery');
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery_add'),base_url().'admincp/gallery/add');
        $data['template'] = 'gallery/add';
        $data['title_page']='<i class="icon20 i-plus-circle-2"></i> '.trans('title_gallery_add');
        $data['catalogue']=$this->Mcataloguemedia->list_all();
        if($this->input->server('REQUEST_METHOD') == "POST"){
            $cata_id = $this->input->post('catalogue');
            $gallery_name = $this->input->post('gallery_name');
            $encry = md5(time().$gallery_name);
            $data_insert = array(
                'cata_id' => $cata_id,
                'gallery_name' => $gallery_name,
                'gallery_name_encryption' => $encry,
                'gallery_description' => $this->input->post('gallery_description'),
                'date_add' => date('Y-m-d',time()), 
            );
            $this->Mgallery->insert($data_insert);
            $this->session->set_flashdata(array("success"=>trans('message_edit_successfully')));
            redirect(base_url()."admincp/gallery");
        }
        $this->load->view('admincp/template', $data);
    }

    public function edit(){
        $id=$this->uri->segment(5);
        $this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery'),base_url().'admincp/gallery');
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery_edit'),base_url().'admincp/gallery/edit/id/'.$id);
        $data['template'] = 'gallery/edit';
        $data['title_page']='<i class="icon20 i-pen-2"></i> '.trans('title_gallery_edit');
        $data['info']=$this->Mgallery->get_data($id);
        $data['catalogue']=$this->Mcataloguemedia->list_all();
        if($this->input->server('REQUEST_METHOD') == "POST"){
            $cata_id = $this->input->post('catalogue');
            $data_update = array(
                'cata_id' => $cata_id,
                'gallery_name' => $this->input->post('gallery_name'),
                'gallery_description' => $this->input->post('gallery_description'),
                'date_edit' => date('Y-m-d',time()), 
            );
            $this->Mgallery->update($data_update,$id);
            $this->session->set_flashdata(array("success"=>trans('message_edit_successfully')));
            redirect(base_url()."admincp/gallery");
        }
        $this->load->view('admincp/template', $data);
    }

    public function upload(){
        $id=$this->uri->segment(5);
        $this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery'),base_url().'admincp/gallery');
        $this->breadcrumb->append_crumb(trans('breadcrumb_gallery_upload'),base_url().'admincp/gallery/upload/id/'.$id);
        $data['template'] = 'gallery/upload';
        $data['title_page']='<i class="icon20 i-file-upload"></i> '.trans('title_gallery_upload');
        $data['info']=$this->Mgallery->get_data($id);
        $data['images']=$this->Mgallery->get_images($id);
        $data['catalogue']=$this->Mcataloguemedia->list_all();
        $this->load->view('admincp/template', $data);
    }

    // Function called by the form
    public function do_upload(){
        $idGal = $this->input->post('idGal');
        $pathGal = $this->input->post('pathGal');

        $upload_dir = './assets/filemanager/gallery/'.$pathGal.'/';
        $thump_dir = './assets/filemanager/gallery/'.$pathGal.'/thumbnails/';

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir);
        }
        if (!is_dir($thump_dir)) {
            mkdir($thump_dir);
        }       

        $allowed_ext = array('jpg','jpeg','png','gif');


        if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
            exit_status('Error! Wrong HTTP method!');
        }

        if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
            
            $pic = $_FILES['pic'];

            if(!in_array(get_extension($pic['name']),$allowed_ext)){
                exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
            }            
            
            // Move the uploaded file from the temporary 
            // directory to the uploads folder:
            
            if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
                $this->GenerateThumbnail($upload_dir.$pic['name'],$thump_dir.$pic['name'],400,600,0.60);

                $this->load->library('image_lib');

                $config['image_library'] = 'gd2';
                $config['source_image'] = $upload_dir.$pic['name'];
                $config['create_thumb'] = FALSE;
                $config['maintain_ratio'] = TRUE;
                $config['width']     = 1280;
                $config['height']   = 720;

                $this->image_lib->clear();
                $this->image_lib->initialize($config);
                $this->image_lib->resize();

                $dataInsertImages = array(
                    'images' => substr($upload_dir.$pic['name'], 2),
                    'thump' => substr($thump_dir.$pic['name'], 2),
                    'gallery_id' => $idGal
                );
                $this->db->insert('tpt_gallery_images',$dataInsertImages);
                exit_status('File was uploaded successfuly!');
            }
            
        }

        exit_status('Something went wrong with your upload!');       
    }

    public function GenerateThumbnail($im_filename,$th_filename,$max_width,$max_height,$quality = 0.75){
    // The original image must exist
    if(is_file($im_filename)){
        // Let's create the directory if needed
        $th_path = dirname($th_filename);
        if(!is_dir($th_path))
            mkdir($th_path, 0777, true);
        // If the thumb does not aleady exists
        if(!is_file($th_filename)){
            // Get Image size info
            list($width_orig, $height_orig, $image_type) = @getimagesize($im_filename);
            if(!$width_orig)
                return 2;
            switch($image_type){
                case 1: $src_im = @imagecreatefromgif($im_filename);    break;
                case 2: $src_im = @imagecreatefromjpeg($im_filename);   break;
                case 3: $src_im = @imagecreatefrompng($im_filename);    break;
            }
            if(!$src_im)
                return 3;
            $aspect_ratio = (float) $height_orig / $width_orig;

            $thumb_height = $max_height;
            $thumb_width = round($thumb_height / $aspect_ratio);
            if($thumb_width > $max_width){
                $thumb_width    = $max_width;
                $thumb_height   = round($thumb_width * $aspect_ratio);
            }

            $width = $thumb_width;
            $height = $thumb_height;

            $dst_img = @imagecreatetruecolor($width, $height);
            if(!$dst_img)
                return 4;
            $success = @imagecopyresampled($dst_img,$src_im,0,0,0,0,$width,$height,$width_orig,$height_orig);
            if(!$success)
                return 4;
            switch ($image_type) {
                case 1: $success = @imagegif($dst_img,$th_filename); break;
                case 2: $success = @imagejpeg($dst_img,$th_filename,intval($quality*100));  break;
                case 3: $success = @imagepng($dst_img,$th_filename,intval($quality*9)); break;
            }
            if(!$success)
                return 4;
        }
        return 0;
    }
    return 1;
    }

    public function delete(){
        $id = $this->uri->segment(5);
        $this->Mgallery->delete($id);
        $this->db->where('gallery_id', $id);
        $rowImages = $this->db->get('tpt_gallery_images')->result_array();
        foreach ($rowImages as $value) {
            unlink(base_url().$value['images']);
            unlink(base_url().$value['thump']);
        }
        $this->session->set_flashdata(array("success"=>trans('message_delete_successfully')));
        redirect(base_url()."admincp/gallery");
    }

    public function deleteImage(){
        $id = $this->input->post('id');
        $this->Mgallery->deleteImage($id);
    }
    
    public function saveOrderImages(){
    	$idGal = $this->input->post('idGal');    	    	
    	$dataJson = $this->input->post('dataJson');
    	$arrData = json_decode($dataJson,1);
    	foreach($arrData as $value){
    		$data = array(
    			'order' => $value['value']
    		);
    		$this->Mgallery->updateOrderImages($idGal, $value['id'], $data);
    	}
    }
}